/*
    video.c
    Use the link-table to solve the problem
    BeginnerC
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Image
{
    char *buffer;
    int width;
    int height;
    struct Image *next;
}Image;
void Clear()
{
    system("clear");
}
void OutputImage(Image *image)
{
    for (int i = 0;i < image -> height;i++)
    {
        for (int j = 0;j < image -> width;j++)
        {
            printf("%c ", *(image -> buffer + i * image -> height + j));
        }
        puts("");
    }
}
Image* GenerateImage(int width, int height)
{
    Image *result = NULL;
    int length = width * height;
    result = (Image*)calloc(1, sizeof(Image));
    if (NULL == result)
    {
        return NULL;
    }
    result -> width = width;
    result -> height = height;
    result -> buffer = (char*)calloc(length, sizeof(char));
    if (NULL == result -> buffer)
    {
        free(result);
        return NULL;
    }
    for (int i = 0;i < length;i++)
    {
        result -> buffer[i] = rand() % 2 + '0';
    }
    return result;
}
void FreeImageList(Image *image)
{
    Image *temp = NULL;
    while (image)
    {
        free(image -> buffer);
        free(image);
        temp = image -> next;
        image = temp;
    }
}
void Sleep(int ms)
{
    register unsigned begin = clock();
    while ((clock() - begin) * 1000 / CLOCKS_PER_SEC < ms)
        ;
}
int main()
{
    Image *first = NULL, *last = NULL, *temp = NULL;
    first = (Image*)calloc(1, sizeof(Image));
    if (NULL == first)
        return -1;
    first = GenerateImage(10, 10);
    if (NULL == first)
    {
        return -1;
    }
    last = first;
    for (int i = 0;i < 24;i++)
    {
        temp = GenerateImage(10, 10);
        if (NULL == temp)
        {
            FreeImageList(first);
            return -1;
        }
        last -> next = temp;
        last = temp;
    }
    while (1)
    {
        temp = first;
        for (int i = 0;i < 24;i++)
        {
            Clear();
            OutputImage(temp);
            temp = temp -> next;
            Sleep(30);
        }
    }
    FreeImageList(first);
    return 0;
}